package com.wmlive.hhvideo.common.base;


import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.umeng.analytics.MobclickAgent;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.heihei.channel.LoginSinaChannelPresenter;
import com.wmlive.hhvideo.heihei.channel.LoginWechatChannelPresenter;
import com.wmlive.hhvideo.heihei.login.LoginDialog;
import com.wmlive.hhvideo.utils.DeviceUtils;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.WeakHandler;
import com.wmlive.hhvideo.widget.dialog.CustomProgressDialog;
import com.wmlive.networklib.util.RxBus;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.wmlive.hhvideo.R;
import io.reactivex.Flowable;
import io.reactivex.disposables.CompositeDisposable;

/**
 * A simple {@link Fragment} subclass.
 * Fragment基类，不含根布局
 */
public abstract class BaseFragment<P extends IBasePresenter> extends Fragment
        implements View.OnClickListener, BaseView {


    protected String requestTag = this.getClass().getSimpleName();
    private Set<IBasePresenter> presenterList = new HashSet<>();
    protected static final String LAZY_MODE = "lazy_mode";
    protected static final String SINGLE_MODE = "single_mode";
    protected boolean isLazyMode = true; //是否懒加载，在子类创建的时候传参数 {@param LAZY_MODE} 进行设置
    protected boolean isVisible = true;    //页面是否已经可见  注意：使用FragmentTabHost或者容器中只有一个fragment，setUserVisibleHint()方法不会被调用，所以需要传true给isVisible，可以通过设置SINGLE_MODE为true或者直接设置isVisible为true
    protected boolean isPrepared = false;    //懒加载是否已经准备好
    protected boolean isLoadFinish = false;    //页面是否已经加载完毕
    protected boolean isFirstLoadData = true;    //首次加载数据
    protected long lastClickTime;
    private int lastViewId;

    protected P presenter;   //页面presenter
    protected View rootView; //base根布局
    private Unbinder unbinder;

    /**
     * 存放订阅的容器,方便统一解除订阅
     */
    CompositeDisposable compositeDisposable;
    private LoginDialog loginDialog;
    private LoginWechatChannelPresenter loginWechatChannelPresenter;
    private LoginSinaChannelPresenter loginSinaChannelPresenter;
    private WeakHandler weakHandler;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        KLog.i("======setUserVisibleHint:" + requestTag + "___isVisibleToUser:" + isVisibleToUser);

        if (isVisibleToUser && isLoadFinish) {
            //刷新页面数据(可见并且页面加载完毕)
            onFragmentVisible();
        } else if (!isVisibleToUser && isLoadFinish) {
            //页面不可见并且页面已经加载完毕
            onFragmentInvisible();
        }
        //懒加载
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    /**
     * 刷新页面数据
     */
    public void onFragmentVisible() {
        KLog.i(requestTag + "========onFragmentVisible");
    }

    public void onFragmentInvisible() {
        KLog.i(requestTag + "========onFragmentInvisible");
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        KLog.i(requestTag + "========onHiddenChanged:" + (hidden ? "不可见" : "可见") + "_getView():" + getView());
        if (getView() != null) {
            getView().setVisibility(hidden ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getArguments() != null) {
            isLazyMode = getArguments().getBoolean(LAZY_MODE);
            isVisible = getArguments().getBoolean(SINGLE_MODE);
        }
        int layoutId = getBaseLayoutId();
        if (rootView == null && layoutId > 0) {
            rootView = inflater.inflate(layoutId, container, false);
        }
        KLog.i(requestTag + "========onCreateView");
        return rootView != null ? rootView : super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        KLog.i(requestTag + "========onViewCreated");
        lazyLoad();
    }

    /**
     * 页面可见时
     */
    protected void onVisible() {
        lazyLoad();
    }

    /**
     * 页面不可见时
     */
    protected void onInvisible() {
    }

    /**
     * 是否懒加载
     */
    protected void lazyLoad() {
        if (isLazyMode && (!isVisible || !isPrepared)) {
            return;
        }
        if (isPrepared) {
            loadAll();
        }
    }

    protected void loadAll() {
        if (!isLoadFinish) {
            KLog.i(requestTag + "====loadAll");
            presenter = getPresenter();
            addPresenter(presenter);
            initBaseView();
            unbinder = ButterKnife.bind(this, rootView);
            initData();
            isLoadFinish = true;
        }
    }

    /**
     * 显示加载进度框
     *
     * @param message    加载信息
     * @param cancelable 是否可手动取消
     */
    public void showLoadingDialog(String message, boolean cancelable) {
        ((BaseCompatActivity) getActivity()).showLoadingDialog(message, cancelable);
    }

    /**
     * 关闭加载进度框
     */
    public void closeLoadingDialog() {
        ((BaseCompatActivity) getActivity()).closeLoadingDialog();
    }

    /**
     * 初始化数据
     */
    protected void initData() {

    }

    /**
     * 获取一个WeakHandler
     *
     * @return
     */
    protected WeakHandler getWeakHandler() {
        if (weakHandler == null) {
            weakHandler = new WeakHandler();
        }
        return weakHandler;
    }

    /**
     * 添加Presenter
     *
     * @param presenters
     */
    protected void addPresenter(IBasePresenter... presenters) {
        for (IBasePresenter presenter : presenters) {
            if (null != presenter) {
                presenter.bindContext(getContext());
                presenterList.add(presenter);
            }
        }
    }

    /**
     * 初始化presenter，只针对泛型方式传入的Presenter
     *
     * @return
     */
    protected P getPresenter() {
        return null;
    }

    /**
     * 获取页面的布局文件
     *
     * @return
     */
    protected abstract int getBaseLayoutId();

    /**
     * 初始化基础布局，Base之间的继承才调用这个方法，其他情况不用
     */
    void initBaseView() {
    }

    /**
     * view的点击事件都在此方法中处理
     *
     * @param v
     */
    protected abstract void onSingleClick(View v);

    /**
     * 控制statusbar和toolbar的显示
     *
     * @param status 0：正常显示toolbar和statubar
     *               1：隐藏toolbar，显示statubar
     *               2：隐藏toolbar和statubar
     *               3：显示toolbar，内容沉浸到statubar（5.0以上有效）
     *               4：隐藏toolbar，内容沉浸到statubar（5.0以上有效）
     */
    protected void changeDecorView(int status) {
        ((BaseCompatActivity) getActivity()).changeDecorView(status);
    }

    @Override
    public void onStop() {
        super.onStop();
        KLog.i("=====onStop:" + requestTag);
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.stop();
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        KLog.i("=====onStart:" + requestTag);
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.start();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        KLog.i("=====onResume:" + requestTag);
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.resume();
            }
        }
        MobclickAgent.onPageStart(requestTag);
    }

    @Override
    public void onPause() {
        super.onPause();
        KLog.i("=====onPause:" + requestTag);
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.pause();
            }
        }
        MobclickAgent.onPageEnd(requestTag);
        DeviceUtils.hiddenKeyBoard(getActivity().findViewById(android.R.id.content));
    }

    @Override
    public void onDestroy() {
        KLog.i("=====onDestroy:" + requestTag);
        Iterator<IBasePresenter> iterator = presenterList.iterator();
        while (iterator.hasNext()) {
            iterator.next().destroy();
            iterator.remove();
        }
        if (null != unbinder) {
            unbinder.unbind();
            unbinder = null;
        }
        if (null != weakHandler) {
            weakHandler.removeCallbacksAndMessages(null);
        }
        if (null != compositeDisposable) {
            compositeDisposable.dispose();
        }

        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        dismissLoad();
        KLog.i("======onDestroyView:" + requestTag);
        ((BaseCompatActivity) getActivity()).removeWeakHandler();
        closeLoadingDialog();


        if (rootView != null) {
            ViewGroup parent = ((ViewGroup) rootView.getParent());
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
    }


    protected CompositeDisposable getCompositeDisposable() {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        return compositeDisposable;
    }

    protected <T> Flowable<T> toFlowable(Class<T> type) {
        return RxBus.getInstance().toFlowable(type);
    }


    /**
     * 特殊情况需要findView
     *
     * @param id
     * @return
     */
    protected View findViewById(int id) {
        return rootView.findViewById(id);
    }

    protected void showToast(String message) {
        ((BaseCompatActivity) getActivity()).showToast(message);
    }

    protected void showToast(int stringId) {
        ((BaseCompatActivity) getActivity()).showToast(stringId);
    }

    @Override
    public void onClick(View v) {
        long currentTime = System.currentTimeMillis();
        if ((lastViewId == v.getId())) {
            if (currentTime - lastClickTime > GlobalParams.Config.MINIMUM_CLICK_DELAY) {
                onSingleClick(v);
            } else {
                KLog.i(requestTag, "快速点击无效");
            }
        } else {
            onSingleClick(v);
        }
        lastViewId = v.getId();
        lastClickTime = currentTime;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            ((BaseCompatActivity) getActivity()).onBack();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void startActivity(String intentName) {
        ((BaseCompatActivity) getActivity()).startActivity(intentName);
    }

    protected String getResString(int resId) {
        return getContext().getResources().getString(resId);
    }

    /**
     * 请求的url错误
     */
    @Override
    public void handleNetError() {
        ToastUtil.showToast(R.string.net_error);
    }

    /**
     * 请求的返回结果错误
     *
     * @param requestCode
     * @param message
     */
    @Override
    public void onRequestDataError(int requestCode, String message) {
        showToast(message);
    }

    public void showReLogin() {
        ((BaseCompatActivity) getActivity()).showReLogin();
    }

    public void loading() {
        ((BaseCompatActivity) getActivity()).loading();
    }

    public CustomProgressDialog loading(boolean cancelable, DialogInterface.OnDismissListener listener) {
        return ((BaseCompatActivity) getActivity()).loading(cancelable, listener);
    }

    public void dismissLoad() {
        ((BaseCompatActivity) getActivity()).dismissLoad();
    }

}
